package com.wuxu.lib_skin_core.res

import android.content.Context
import android.content.res.Resources
import android.graphics.drawable.Drawable
import android.util.Log
import androidx.core.content.ContextCompat
import androidx.core.content.res.ResourcesCompat
import com.wuxu.lib_skin_core.load.SkinLoadStrategy

/**
 *@author wuxu
 *@date 2024/5/21 10:42
 *@description 资源统一处理类
 */
object ResourceSingleton {
    private var mResource: Resources? = null
    private var mSkinName:String? = null // 皮肤包名，当加载APK中的资源时使用。
    private var mPkgName:String? = null
    private var mSkinLoadStrategy:SkinLoadStrategy? = null

    private var isDefaultSkin = true

    fun getResource() = mResource

    private fun reset(){
        this.mResource = null
        this.mSkinName = null
        this.mPkgName = null
        isDefaultSkin=true
    }

    fun setupSkin(resource: Resources?,pkgName:String?,skinName:String?,skinLoadStrategy: SkinLoadStrategy){
        if(resource == null || pkgName.isNullOrEmpty()||skinName.isNullOrEmpty()){
            reset()
            return
        }
        Log.i("wuxu", "setupSkin")
        this.mResource = resource
        this.mPkgName=pkgName
        this.mSkinName=skinName
        isDefaultSkin = false
        this.mSkinLoadStrategy=skinLoadStrategy
    }

    fun getColor(context: Context, resId: Int): Int {
        var realColorId: Int = -1
        getResource()?.let { res ->
            val entryName = mSkinLoadStrategy?.getResourceEntryName(context, mSkinName!!,resId)
            realColorId = context.getColor(res.getIdentifier(entryName, "color", context.packageName))
            Log.i("wuxu","--$realColorId,entryName:$entryName")
        }
        return realColorId
    }

    //关于获取Drawable 及加载流程，需要以后通过源码学习掌握
    fun getDrawable(context: Context, resId: Int): Drawable? {
        var drawable:Drawable?=null
        getResource()?.let { res ->
//            val entryName = mSkinLoadStrategy?.getResourceEntryName(context, mSkinName!!,resId)
//            val drawableId = res.getIdentifier(entryName, "drawable", mPkgName)
//            val oldDrawableId = context.resources.getIdentifier(entryName, "drawable", context.packageName)
            drawable= ResourcesCompat.getDrawable(res,resId,null) // 图片资源不同于color 等其他资源，这个id与宿主app是相同的，通过resources对象取出apk目录下的图片资源。
//            Log.i("wuxu","entryName:$entryName,drawableID:$drawableId,oldDrawableId:$oldDrawableId,res:$res,oldRes:${context.resources}")
        }
        return drawable
    }
}